const CONFIG = require('../../config.js');
const app = getApp()
Page({

  /**
   * 页面的初始数据
   */
  data: {
	navBgColor: '-webkit-gradient(linear, 0% 0%, 0% 100%,from(#1b64e5), to(#488dea))',
	isShowBtn: true,
	loginInfo: {},
	wxQRcode: '',
	QRImg: '',
	posterContent: '',

    bgImg:"../../images/share.jpg",
	maskHidden: false,
    name:"",
	touxiang:"",
	imagePath:"",
	navBarHeight: 0,
	canIUseGetUserProfile: false,
  },
	ready() {
		let {
			navBarHeight
		} = app.globalData;
		this.setData({
			navBarHeight
		})
	},
  
	// 获取用户小程序码
	getWxCode(){		
		let that = this;
		wx.request({
			url: CONFIG.host + "/system/user/getUserShareCodePic",
			data: {},
			method: "GET",
			header: {
				'content-type': 'application/json',
				'Authorization': this.data.loginInfo.token
			},
			success: res => {
				if(res.data.code === 'success'){
					let datas = res.data.data;
					this.setData({
						wxQRcode: datas.shareCode,
						posterContent: datas.posterContent,
					})
					wx.downloadFile({
						url: this.data.wxQRcode, 
						success(downloadRes) {
							if (downloadRes.statusCode === 200) {
								that.setData({
									QRImg: downloadRes.tempFilePath,
								})
							}
						}
					})
					wx.getSetting({
						success: res => {
							let isShow = true
							if (res.authSetting['scope.userInfo']) {
								isShow = false;
								that.getUserFn();
							}
							that.setData({
								isShowBtn: isShow
							})
						}
					})
				}
			},fail: function (error) {
				console.log(error);
			}
		})
	},
	
	// 已经授权，可以直接调用 getUserInfo 获取头像昵称
	getUserFn(e){
		let that = this;
		if(this.data.canIUseGetUserProfile){
			wx.getUserProfile({
				desc: '用于完善分享图片信息', // 声明获取用户个人信息后的用途，后续会展示在弹窗中，请谨慎填写
				success: (resInfo) => {
					that.saveUserInfo(resInfo.userInfo);
				}
			})
		}else{
			that.saveUserInfo(e.detail.userInfo);
			// wx.getUserInfo({
			// 	success: resInfo => {
			// 		that.saveUserInfo(resInfo);
			// 	}
			// })
		}
	},

	// 获取到用户头像信息，执行图片下载
	saveUserInfo(userInfo){
		let that = this;
		let str = userInfo.avatarUrl;
		let url = str.substring(str.indexOf('mmopen'),str.length);
		let url2 = url.substring(0, url.lastIndexOf('/'));
		let downloadUrl = CONFIG.url + 'wxpic/' + url2 + '/0';
		wx.downloadFile({
			url: downloadUrl, 
			success(downloadRes) {
				if (downloadRes.statusCode === 200) {
					that.setData({
						touxiang: downloadRes.tempFilePath,
						nickName: userInfo.nickName,
					})
				}
			}
		})
	},
	
	// 用户 授权后回调
	bindGetUserInfo (e) {
		if(e.detail.userInfo){
			this.getUserFn();
			this.setData({
				isShowBtn: false
			})
		}
	},

	/**
	 * 生命周期函数--监听页面加载
	 */
	onLoad: function (options) {
		if (wx.getUserProfile) {
			this.setData({
			  canIUseGetUserProfile: true
			})
		}
		let loginInfo = wx.getStorageSync('loginInfo') || '';
		if(loginInfo){
			this.setData({
				loginInfo : JSON.parse(loginInfo)
			})
			this.getWxCode();
		}
		console.log(wx.getSystemInfoSync().windowWidth,123)
		console.log(wx.getSystemInfoSync().windowHeight,456)
	},
	

	//点击生成图片
	formSubmit: function (e) {
		var that = this;
		this.setData({
			maskHidden: false
		});
		wx.showToast({
			title: '图片生成中...',
			icon: 'loading',
			duration: 1000
		});
		setTimeout(function () {
			wx.hideToast()
			that.createNewImg();
			that.setData({
				maskHidden: true
			});
		}, 1000)
	},

	//将canvas转换为图片保存到本地，然后将图片路径传给image图片的src
	createNewImg: function () {
		var that = this;
		var context = wx.createCanvasContext('mycanvas');
		context.fillRect(0, 0, 375, 600)
		var path = "/images/share.jpg";
		//将模板图片绘制到canvas,在开发工具中drawImage()函数有问题，不显示图片
		//不知道是什么原因，手机环境能正常显示
		context.drawImage(path, 0, 0, 375, 600);
		//将模板图片绘制到canvas,在开发工具中drawImage()函数有问题，不显示图片
		//不知道是什么原因，手机环境能正常显示
		// context.save(); // 保存当前context的状态

		//绘制名字
		context.setFontSize(16);
		context.setFillStyle('#333333');
		context.setTextAlign('center');
		context.fillText(that.data.posterContent, 185, 205);
		context.stroke();

		context.setFontSize(16);
		context.setFillStyle('#000');
		context.setTextAlign('center');
		context.fillText("邀请好友扫描二维码  让TA获得专属优惠", 180, 450);

		context.stroke();
		context.setFontSize(16);
		context.setFillStyle('#000');
		context.setTextAlign('center');
		context.fillText("您也获好友消费奖励  最高返20%收益", 180, 480);
		context.stroke();

		// 绘制微信二维码
		context.drawImage(that.data.QRImg, 90, 220, 200, 200);

		// 绘制头像
		var path1 = that.data.touxiang;
		context.arc(181, 77, 45, 0, 2 * Math.PI) //画出圆
		context.clip(); //裁剪上面的圆形
		context.drawImage(path1, 136, 32, 90, 90); // 在刚刚裁剪的园上画图
		
		context.draw();
		
		//将生成好的图片保存到本地，需要延迟一会，绘制期间耗时
		setTimeout(function () {
			wx.canvasToTempFilePath({
				canvasId: 'mycanvas',
				success: function (res) {
				var tempFilePath = res.tempFilePath;
				that.setData({
					imagePath: tempFilePath,
					canvasHidden:true
				});
				},
				fail: function (res) {
				console.log(res);
				}
			});
		}, 200);
	},
	//点击保存到相册
	baocun:function(){
		let that = this;
		// 可以通过 wx.getSetting 先查询一下用户是否授权了 "scope.record" 这个 scope
		wx.getSetting({
			success(res) {
				if (!res.authSetting['scope.writePhotosAlbum']) {
					wx.authorize({
						scope: 'scope.writePhotosAlbum',
						success (res) {
							// 用户已经同意小程序使用录音功能，后续调用 wx.startRecord 接口不会弹窗询问
							// wx.startRecord()
							wx.openSetting({
								success(res) {
									console.log(res)
								}
							})
							that.saveImageToLocal()
						},
						fail(err) {
							wx.showModal({
								title: '授权',
								content: '不授权，将无法保存图片',
								showCancel: false,
								confirmText: '请授权',
								success (res) {
									if (res.confirm) {
										wx.openSetting({
											success(res) {
												console.log(res)
											}
										})
									}
								}
							})
						}
					})
				} else {
					that.saveImageToLocal()
				}
			},
			fail(err) {
				console.log(err)
			}
		})
	},

	// 保存图片到本地
	saveImageToLocal(){
		let that = this;
		wx.saveImageToPhotosAlbum({
			filePath: that.data.imagePath,
			success(res) {
				console.log(res,12321)
				wx.showModal({
				content: '图片已保存到相册，赶紧晒一下吧~',
				showCancel: false,
				confirmText: '好的',
				confirmColor: '#333',
				success: function (res) {
					if (res.confirm) {
						console.log('用户点击确定');
						/* 该隐藏的隐藏 */
						that.setData({
							maskHidden: false
						})
					}
				},fail:function(res){
					console.log(11111)
				}
				})
			},fail:function(res){
				console.log(res, 2222222)
			}
		})
	},

	// 取消保存图片
	cancelBtn(){
		this.setData({
			maskHidden: false
		})
	},

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {
  
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
	  
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {
  
  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {
  
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {
  
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {
  
  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function (res) {
    return {
      title:"这个是我分享出来的东西",
      success:function(res){
        console.log(res,"转发成功")
      },
      fail:function(res){
        console.log(res,"转发失败")
      }
    }
  }
})